/*
 * @Description: 移交登记上下文
 * @Author: Rfan
 * @Date: 2022-11-19 10:27:03
 * @LastEditTime: 2022-11-19 15:32:10
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import {
  SET_SELECT_AT,
  SET_SELECT_AT_ID,
  SET_SELECT_FOND,
  SET_SELECT_FOND_ID,
  SET_PENDING_LIST,
  DELETE_REGISTRATION_ITEM,
  SET_SELECTED_ITEM
} from '../constants';
import { CatalogueReducer } from '../reducers/CatalogueReducer';
import { message, Modal } from 'antd';
import { deletePendingDisposition, fetchPendingListByPage } from '@/api/archives/disposition';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectFondId: 0,
  selectATId: 0,
  // 选中的表格条目
  selectItems: [],

  list: [],

  // -------- 字典 --------
  // 数据来源
  sourcesList: [
    { id: 0, name: '手动添加' },
    { id: 1, name: '自动添加' }
  ],
  // 数据来源
  stateList: [
    { id: 0, name: '待鉴定' },
    { id: 1, name: '鉴定中' },
    { id: 2, name: '待处置' },
    { id: 3, name: '待销毁' },
    { id: 4, name: '处置完成' }
  ]
};

const CatalogueContext = createContext();

const CatalogueProvider = (props) => {
  const [state, dispatch] = useReducer(CatalogueReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的全宗
     */
    setSelectFondId(id) {
      dispatch({ type: SET_SELECT_FOND_ID, id });
    },

    /**
     * @description: 设置选中的档案类型ID
     */
    setSelectATId(id) {
      dispatch({ type: SET_SELECT_AT_ID, id });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    getPendingList(query) {
      return new Promise((resolve, reject) => {
        fetchPendingListByPage(query)
          .then((res) => {
            const { data } = res;
            console.log('pending', data);
            dispatch({
              type: SET_PENDING_LIST,
              data: data.results
            });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    deleteItem(id, title = '是否移除选中的登记条目?') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deletePendingDisposition(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            message.success('删除成功');
            dispatch({ type: DELETE_REGISTRATION_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('del item Cancel');
        }
      });
    }
  };

  const filters = {
    sourcesFilter(id) {
      return state.sourcesList.find((item) => item.id === id)?.name || '-';
    },
    stateFilter(id) {
      return state.stateList.find((item) => item.id === id)?.name || '-';
    }
  };

  useEffect(() => {}, []);

  return (
    <CatalogueContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </CatalogueContext.Provider>
  );
};

export const useCatalogueContext = () => {
  return useContext(CatalogueContext);
};

export { CatalogueContext, CatalogueProvider };
